package com.iotimc.attendancesystem.manage.person;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.iotimc.attendancesystem.R;
import com.iotimc.attendancesystem.activity.AddHeadActivity;
import com.iotimc.attendancesystem.base.BaseFragment;
import com.iotimc.attendancesystem.dao.GreenDaoManager;
import com.iotimc.attendancesystem.dao.PersonEntityDao;
import com.iotimc.attendancesystem.entity.PageHelper;
import com.iotimc.attendancesystem.entity.PersonEntity;
import com.iotimc.attendancesystem.event.CardEvent;
import com.iotimc.attendancesystem.util.CustomDialog;
import com.iotimc.attendancesystem.util.TtsUtil;
import com.iotimc.networklibrary.core.BaseObserver;
import com.iotimc.networklibrary.core.HttpRetrofitFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.greenrobot.greendao.query.QueryBuilder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author david
 * @date 2017/11/28
 */

public class PersonManageFragment extends BaseFragment implements PersonContract.DeleteView {
    private static final String TAG = "PersonManageFragment";
    PersonDialog dialog;
    PersonEntityDao personEntityDao;

    @BindView(R.id.page_num)
    TextView pageNum;
    @BindView(R.id.et_manage_search)
    EditText mEtManageSearch;
    @BindView(R.id.bt_manage_search)
    Button mBtManageSearch;
    @BindView(R.id.ll_manage_search)
    LinearLayout mLlManageSearch;
    @BindView(R.id.ll_manage_edit)
    LinearLayout mLlManageEdit;
    @BindView(R.id.bt_manage_edit)
    Button mBtManageEdit;
    @BindView(R.id.bt_manage_edit_all)
    Button mBtManageEditAll;
    @BindView(R.id.rc_manage_user)
    RecyclerView mRcManageUser;
    @BindView(R.id.page_head)
    TextView mPageHead;
    @BindView(R.id.page_up)
    TextView mPageUp;
    @BindView(R.id.page_next)
    TextView mPageNext;
    @BindView(R.id.page_end)
    TextView mPageEnd;


    private PersonManageAdapter mAdapter;
    private PageHelper<PersonEntity> personEntityPageHelper;
    private PersonContract.Presenter mPresenter;
    private QueryBuilder mQueryBuilder;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        personEntityDao = GreenDaoManager.getInstance().getSession().getPersonEntityDao();
    }

    @OnClick(R.id.bt_manage_edit)
    void editUser() {
        dialog.setPersonEntity(null);
        dialog.show();
    }

    @OnClick(R.id.bt_manage_all)
    void allUser() {
        mAdapter.selectAll(personEntityPageHelper.getCurrentPage(),true);
    }

    @OnClick(R.id.bt_manage_cancel)
    void cancelUser() {
        mLlManageSearch.setVisibility(View.VISIBLE);
        mLlManageEdit.setVisibility(View.GONE);
        mAdapter.setEditStatus(false);
        mAdapter.selectAll(personEntityPageHelper.getCurrentPage(),false);
        notifyDataChange();
    }

    @OnClick(R.id.bt_manage_edit_all)
    void all() {
        mAdapter.setEditStatus(true);
        alterAll();
    }


    private AlertDialog dialogItem;
    private CustomDialog customdialog;

    @OnClick(R.id.bt_manage_delete)
    void deleteUser() {
        final List<PersonEntity> selected = mAdapter.getSelected();
        if (selected.size() < 1) {
            TtsUtil.ttsSpeek2("请先选择人员");
        } else {
            if (customdialog == null) {
                View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_delete_person, null);

                customdialog = new CustomDialog.Builder(getContext())
                        .setContentView(view)
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                customdialog.dismiss();
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mPresenter.deletePersons(selected);
                                mAdapter.selectAll(personEntityPageHelper.getCurrentPage(),false);
                                customdialog.dismiss();
                            }
                        }).build();
            } else {
                customdialog.show();
            }
        }

    }


    @OnClick(R.id.bt_manage_search)
    void searchUser() {
        String s = String.valueOf(mEtManageSearch.getText());
        QueryBuilder queryBuilder = personEntityDao.queryBuilder();

        if (TextUtils.isEmpty(s)) {
            personEntityPageHelper.headPage();
            queryBuilder.orderDesc(PersonEntityDao.Properties.CreateTime);
            personEntityPageHelper.setQueryBuilder(queryBuilder);
            notifyDataChange();
        } else {
            personEntityPageHelper.headPage();
            queryBuilder.whereOr(PersonEntityDao.Properties.Code.like("%" + s + "%")
                    , PersonEntityDao.Properties.Name.like("%" + s + "%"));
            queryBuilder.orderDesc(PersonEntityDao.Properties.Code);
            personEntityPageHelper.setQueryBuilder(queryBuilder);
            notifyDataChange();
        }

        hideKeyboard();
    }

    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        View focus = getActivity().getCurrentFocus();
        if (imm != null && focus != null) {
            imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    protected int getResId() {
        return R.layout.fragment_person_manage;
    }

    private void testHttp() {
        List<PersonEntity> personEntities = personEntityDao.loadAll();
        String json = JSON.toJSONString(personEntities);
        Map<String, String> map = new HashMap<>(1);
        map.put("json", json);
        HttpRetrofitFactory.getInstance().postToObject("http://192.168.1.45:9527/sync", map,
                new BaseObserver<String>(getActivity(), false) {

                    @Override
                    protected void onHandleSuccess(String o) {
                        Log.i(TAG, "onHandleSuccess: " + o);
                    }

                    @Override
                    protected void onHandleError(String msg) {
                        Log.i(TAG, "onHandleError: " + msg);
                    }

                });
    }

    Intent intent;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        intent = new Intent(getActivity(), AddHeadActivity.class);
        mPresenter = new PersonPresenter(this);
        dialog = new PersonDialog(this, mPresenter);


        mQueryBuilder = personEntityDao.queryBuilder();

        personEntityPageHelper = new PageHelper<>(10);


        mQueryBuilder.orderDesc(PersonEntityDao.Properties.CreateTime);
        personEntityPageHelper.setQueryBuilder(mQueryBuilder);
        pageNum.setText(personEntityPageHelper.getCurrentPage() + "/" + (personEntityPageHelper.getPageNum() == 0 ? 1 : personEntityPageHelper.getPageNum()));

        mAdapter = new PersonManageAdapter(mPresenter, getActivity(), dialog, this, personEntityPageHelper);
        mRcManageUser.setLayoutManager(new LinearLayoutManager(getActivity(), 1, false));
        mRcManageUser.setAdapter(mAdapter);
        //testHttp();
    }


    @Override
    public void onActivityResult(int requestCode, final int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                dialog.setImageBitmap(resultCode);
            }
        }, 1000);

    }

    public void notifyDataChange() {
        mAdapter.addData(personEntityPageHelper.getData());
        pageNum.setText(personEntityPageHelper.getCurrentPage() + "/" + (personEntityPageHelper.getPageNum() == 0 ? 1 : personEntityPageHelper.getPageNum()));
    }

    public void notifyData() {
        List data = personEntityPageHelper.getData();
        if (data.size() <= 0) {
            personEntityPageHelper.prePage();
        }
        personEntityPageHelper.setQueryBuilder(mQueryBuilder);
        pageNum.setText(personEntityPageHelper.getCurrentPage() + "/" + (personEntityPageHelper.getPageNum() == 0 ? 1 : personEntityPageHelper.getPageNum()));
        mAdapter.addData(personEntityPageHelper.getData());
    }


    @Override
    public void onResume() {
        super.onResume();
        View view = new View(getActivity());
        view.setId(R.id.page_head);
        onViewClicked(view);
    }

    @OnClick({R.id.page_head, R.id.page_up, R.id.page_num, R.id.page_next, R.id.page_end})
    public void onViewClicked(View view) {
        hideKeyboard();
        switch (view.getId()) {
            case R.id.page_head:
                personEntityPageHelper.headPage();
                break;
            case R.id.page_up:
                if (personEntityPageHelper.hasPrePage()) {
                    personEntityPageHelper.prePage();
                } else {
                    return;
                }
                break;
            case R.id.page_num:
                break;
            case R.id.page_next:
                if (personEntityPageHelper.hasNextPage()) {
                    personEntityPageHelper.nextPage();
                } else {
                    return;
                }
                break;
            case R.id.page_end:
                personEntityPageHelper.lastPage();
                break;
            default:
                break;
        }

        notifyDataChange();
    }


    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCardEvent(CardEvent event) {
        Log.i(TAG, "onNotificatonMessage: 收到消息了");
        if (dialog.isShowing()) {
            dialog.setCard(event.getCard());
        }
    }

    public void startBitmap() {
        startActivityForResult(intent, 1);
    }

    @Override
    public void deleteSuccess() {
        TtsUtil.ttsSpeek2("删除成功");
        notifyData();
    }

    public void alterAll() {
        mLlManageSearch.setVisibility(View.GONE);
        mLlManageEdit.setVisibility(View.VISIBLE);
        notifyDataChange();
    }
}
